
#include "rrCintamaniUrl.h"

#include "curl/curl.h"
#pragma comment( lib , "libcurl.lib" )

struct MemoryStruct {
  char *memory;
  size_t size;
};

static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
  size_t realsize = size * nmemb;
  struct MemoryStruct *mem = (struct MemoryStruct *)userp;
 
  mem->memory = (char*)realloc(mem->memory, mem->size + realsize + 1);
  if (mem->memory == NULL) {
    /* out of memory! */ 
    printf("not enough memory (realloc returned NULL)\n");
    exit(EXIT_FAILURE);
  }
 
  memcpy(&(mem->memory[mem->size]), contents, realsize);
  mem->size += realsize;
  mem->memory[mem->size] = 0;
 
  return realsize;
}
 
char * rrCintamaniUrl::GetData( const std::string & Url, long & ReturnCode )
{
	CURL *curl_handle = NULL;

	chunk = new MemoryStruct();

	chunk->memory = (char*)malloc(1);  /* will be grown as needed by the realloc above */ 
	chunk->size = 0;    /* no data at this point */ 

	//curl_global_init(CURL_GLOBAL_ALL);

	/* init the curl session */ 
	curl_handle = curl_easy_init();

	if(!curl_handle){}  //MessageBox(0,s2ws( "Curl init Failed !"  ).c_str(), s2ws( "Curl init Failed !"   ).c_str(),0);

	/* specify URL to get */ 
	curl_easy_setopt(curl_handle, CURLOPT_URL, Url.c_str());
	/* some servers don't like requests that are made without a user-agent field, so we provide one */ 
	curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.6 (KHTML, like Gecko) Chrome/16.0.897.0 Safari/535.6");

	//curl_easy_setopt(curl_handle, CURLOPT_HEADER, true);

	curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, true);

	/* send all data to this function  */ 
	curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);

	/* we pass our 'chunk' struct to the callback function */ 
	curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)chunk);

	/* get it! */ 
	CURLcode code = curl_easy_perform(curl_handle);
	if(  code != CURLE_OK) {   }// MessageBox(0,s2ws( "curl_easy_perform failed"  ).c_str(), s2ws( "curl_easy_perform failed"  ).c_str(),0);

	curl_easy_getinfo (curl_handle, CURLINFO_RESPONSE_CODE, &ReturnCode);

	//char val[255];
	//sprintf( val,"%d bytes retrieved\n", (long)chunk->size);

	curl_easy_cleanup(curl_handle);

	return chunk->memory;
 
}
